import React, { Component } from "react";
import { Layout, ConfigProvider, Spin } from "antd";
import zhCN from "antd/lib/locale-provider/zh_CN";
import { connect } from "dva";
import { withRouter } from "react-router";
import Exception from "../Exception/Exception";
import BaseMenu from "../menu";
import TopHeader from "../header/TopHeader";
import TopBreadcrumb from "../breadcrumb/TopBreadcrumb";
// import menuList from "./menu";
import styles from "./BaseLayout.less";

const { Content } = Layout;
// const arr = [
//   {
//     key: "intell",
//     name: "智能推送"
//   },
//   {
//     key: "messag",
//     name: "消息总线管理"
//   },
//   {
//     key: "system",
//     name: "系统管理"
//   },
//   {
//     key: "docume",
//     name: "帮助文档"
//   }
// ];

@withRouter
@connect(({ user: { userInfo, menuData = [], tenantList } }) => ({
  userInfo,
  menuData,
  tenantList
}))
class BaseLayout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
      menuType: "智能推送",
      menuArr: []
    };
  }

  componentDidMount() {
    // 开发时注释，生成时放开
    const { dispatch } = this.props;
    dispatch({
      type: "user/getUserInfo"
    });
    this.getMenuList();
  }

  componentDidUpdate(prevProps) {
    const {
      location: { pathname },
      menuData = []
    } = this.props;
    if (prevProps.location.pathname !== pathname && Array.isArray(menuData)) {
      this.getAuthority();
    }
  }

  getAuthority = () => {
    const { menuData = [], history } = this.props;
    // const { location: { pathname = "" } = {} } = this.props;
    // const prefix = pathname.substring(1, 7);
    // const current = arr.find((k) => k.key === prefix)||{};
    const menuType = this.findTypeByRoute(menuData);

    // if(!Array.isArray(menuData)){
    //   return;
    // }
    // 无菜单信息跳转到403
    if (!Array.isArray(menuData)) {
      history.push("/exception/403");
      return;
    }

    const exit = menuData.find(k => k.name === menuType);
    if (menuType === "帮助文档") {
      history.push("/document");
    } else if (!exit) {
      // history.push("/intellPush/exception");
    }
    this.setState({
      menuType,
      menuArr: menuData
    });
  };

  findTypeByRoute = menuData => {
    let menuTypeTemp = "";
    menuData.forEach(data => {
      if (window.location.href.indexOf(data.url) !== -1) {
        menuTypeTemp = data.name;
        return;
      }
      if (data.children && data.children.length > 0) {
        data.children.forEach(data1 => {
          if (window.location.href.indexOf(data1.url) !== -1) {
            menuTypeTemp = data.name;
            return;
          }
          if (data1.children && data1.children.length > 0) {
            data1.children.forEach(data2 => {
              if (window.location.href.indexOf(data2.url) !== -1) {
                menuTypeTemp = data.name;
              }
            });
          }
        });
      }
    });
    return menuTypeTemp;
  };

  getMenuList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: "user/getMenu"
    }).then(() => {
      this.getAuthority();
    });
  };

  onCollapse = () => {
    this.setState({ collapsed: !this.state.collapsed }, () => {
      this.props.dispatch({
        type: "user/saveCollapse",
        payload: this.state.collapsed
      });
    });
  };

  onMenuClick = e => {
    const { history } = this.props;
    if (e && e.key === "userManager") {
      history.push("/messageCenter/personalInfoMgt/userManagement");
    }
    if (e && e.key === "logout") {
      // window.location.href = "http://8.129.223.130/login";
      this.props.dispatch({
        type: "user/logout"
      });
      // window.location.href = "https://xxzx.hzos.hzs.zj/mgt/logout";
      // window.location.href =
      // "https://adobe.idpsso.net:8040/public/sp/sso/adobejwt7?enterpriseId=adobe";
    }
  };

  setMenu = e => {
    this.setState(
      {
        menuType: e
      },
      () => {
        const { history } = this.props;
        if (e === "系统管理") {
          history.push("/systemManager/systemMessage/operateLog");
        }
        if (e === "智能推送") {
          history.push("/intellPush/home");
        }
        if (e === "消息总线管理") {
          history.push("/messageCenter/messageManager/messageSource");
        }
        if (e === "帮助文档") {
          history.push("/document");
        }
      }
    );
  };

  render() {
    const {
      children,
      userInfo = {},
      location,
      tenantList,
    } = this.props;
    const { menuType = "智能推送", collapsed, menuArr } = this.state;
    const noneMargin = location.search.includes("showHeader");
    let siderMenu;
    if (menuType === "帮助文档") {
      siderMenu = [
        { key: "1", name: "帮助文档下载", icon: "download", url: "document" }
      ];
    } else {
      siderMenu = menuArr.find(k => k.name === menuType) || {};
      siderMenu = siderMenu.children;
    }
    const topMenu = menuArr.map(item => item.name);

    // 如果未登录状态，则不加载 Layout
    if (!userInfo.userId || !userInfo.userName) {
      return (
        <div
          style={{
            width: "100vw",
            height: "100vh",
            display: "flex",
            alignItems: "center",
            justifyContent: "center"
          }}
        >
          <Spin tip="加载中..." />
        </div>
      );
    }

    // 如果已登录状态，且没有租户信息，则返回租户错误页
    if (userInfo.userName && tenantList.length === 0) {
      const msg =
        "当前登录用户租户信息为空, 请联系管理员添加租户以继续使用系统!";
      return <Exception type={403} desc={msg} manual={true} />;
    }

    return (
      <div className={styles.root}>
        <ConfigProvider locale={zhCN}>
          <Layout className={styles.root}>
            <TopHeader
              userInfo={userInfo}
              tenantList={tenantList}
              onMenuClick={this.onMenuClick}
              setMenu={this.setMenu}
              menuType={menuType}
              data={topMenu}
            />
            <Layout>
              <BaseMenu
                collapsed={collapsed}
                data={siderMenu}
                onCollapse={this.onCollapse}
                menuType={menuType}
              />
              <Content className={`${styles.content}`}>
                {location.pathname === "/intellPush/home" ? null : (
                  <div className={`${noneMargin && styles.noneMargin}`}>
                    <TopBreadcrumb paths={location.pathname} />
                  </div>
                )}
                {children}
              </Content>
            </Layout>
          </Layout>
        </ConfigProvider>
      </div>
    );
  }
}

export default BaseLayout;
